using DeviceRepairWorkflow.Api.Models;
using Microsoft.EntityFrameworkCore;

namespace DeviceRepairWorkflow.Api.Data;

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    public DbSet<Device> Devices { get; set; }
    public DbSet<RepairRequest> RepairRequests { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<ExternalVendor> ExternalVendors { get; set; }
    public DbSet<WorkflowInstance> WorkflowInstances { get; set; }
    public DbSet<WorkflowStep> WorkflowSteps { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Device>(entity =>
        {
            entity.HasKey(e => e.Id);
            entity.Property(e => e.Name).IsRequired().HasMaxLength(200);
            entity.Property(e => e.SerialNumber).IsRequired().HasMaxLength(100);
            entity.Property(e => e.Model).HasMaxLength(100);
            entity.Property(e => e.Location).HasMaxLength(200);
            entity.HasIndex(e => e.SerialNumber).IsUnique();
        });

        modelBuilder.Entity<RepairRequest>(entity =>
        {
            entity.HasKey(e => e.Id);
            entity.Property(e => e.Title).IsRequired().HasMaxLength(200);
            entity.Property(e => e.Description).HasMaxLength(1000);
            entity.Property(e => e.RequestedBy).IsRequired().HasMaxLength(100);
            entity.Property(e => e.AssignedTo).HasMaxLength(100);
            entity.Property(e => e.Notes).HasMaxLength(2000);
            entity.Property(e => e.EstimatedCost).HasColumnType("decimal(18,2)");
            entity.Property(e => e.ActualCost).HasColumnType("decimal(18,2)");

            entity.HasOne(e => e.Device)
                  .WithMany(d => d.RepairRequests)
                  .HasForeignKey(e => e.DeviceId)
                  .OnDelete(DeleteBehavior.Cascade);
                  
            entity.HasOne(e => e.RequestedByUser)
                  .WithMany()
                  .HasForeignKey(e => e.RequestedByUserId)
                  .OnDelete(DeleteBehavior.SetNull);
                  
            entity.HasOne(e => e.AssignedToUser)
                  .WithMany()
                  .HasForeignKey(e => e.AssignedToUserId)
                  .OnDelete(DeleteBehavior.SetNull);
        });

        modelBuilder.Entity<User>(entity =>
        {
            entity.HasKey(e => e.Id);
            entity.Property(e => e.Username).IsRequired().HasMaxLength(100);
            entity.Property(e => e.FullName).IsRequired().HasMaxLength(200);
            entity.Property(e => e.Email).IsRequired().HasMaxLength(200);
            entity.Property(e => e.Phone).HasMaxLength(50);
            entity.Property(e => e.Department).HasMaxLength(100);
            entity.HasIndex(e => e.Username).IsUnique();
            entity.HasIndex(e => e.Email).IsUnique();
        });

        modelBuilder.Entity<ExternalVendor>(entity =>
        {
            entity.HasKey(e => e.Id);
            entity.Property(e => e.CompanyName).IsRequired().HasMaxLength(200);
            entity.Property(e => e.ContactPerson).IsRequired().HasMaxLength(100);
            entity.Property(e => e.ContactPhone).HasMaxLength(50);
            entity.Property(e => e.ContactEmail).HasMaxLength(200);
            entity.Property(e => e.Address).HasMaxLength(500);
            entity.Property(e => e.Notes).HasMaxLength(1000);
        });

        modelBuilder.Entity<WorkflowInstance>(entity =>
        {
            entity.HasKey(e => e.Id);
            entity.Property(e => e.ElsaWorkflowInstanceId).IsRequired().HasMaxLength(100);
            entity.Property(e => e.CurrentStep).IsRequired().HasMaxLength(100);
            entity.Property(e => e.CreatedBy).HasMaxLength(100);
            entity.Property(e => e.RepairContent).HasMaxLength(1000);
            entity.Property(e => e.RepairNotes).HasMaxLength(2000);
            entity.Property(e => e.RepairCost).HasColumnType("decimal(18,2)");
            entity.Property(e => e.ApprovalNotes).HasMaxLength(1000);
            entity.Property(e => e.ApprovedBy).HasMaxLength(100);

            entity.HasOne(e => e.RepairRequest)
                  .WithOne(r => r.WorkflowInstance)
                  .HasForeignKey<WorkflowInstance>(e => e.RepairRequestId)
                  .OnDelete(DeleteBehavior.Cascade);
                  
            entity.HasOne(e => e.ExternalVendor)
                  .WithMany()
                  .HasForeignKey(e => e.ExternalVendorId)
                  .OnDelete(DeleteBehavior.SetNull);
        });

        modelBuilder.Entity<WorkflowStep>(entity =>
        {
            entity.HasKey(e => e.Id);
            entity.Property(e => e.StepName).IsRequired().HasMaxLength(200);
            entity.Property(e => e.StepType).IsRequired().HasMaxLength(100);
            entity.Property(e => e.CompletedBy).HasMaxLength(100);

            entity.HasOne(e => e.WorkflowInstance)
                  .WithMany(w => w.Steps)
                  .HasForeignKey(e => e.WorkflowInstanceId)
                  .OnDelete(DeleteBehavior.Cascade);
        });

        // Seed data
        modelBuilder.Entity<Device>().HasData(
            new Device
            {
                Id = 1,
                Name = "生产线设备A",
                SerialNumber = "DEV001",
                Model = "Model-X1",
                Location = "车间1",
                Status = DeviceStatus.Normal,
                CreatedAt = DateTime.Now.AddDays(-30)
            },
            new Device
            {
                Id = 2,
                Name = "检测设备B",
                SerialNumber = "DEV002",
                Model = "Model-Y2",
                Location = "车间2",
                Status = DeviceStatus.NeedsMaintenance,
                CreatedAt = DateTime.Now.AddDays(-60)
            }
        );

        modelBuilder.Entity<User>().HasData(
            new User
            {
                Id = 1,
                Username = "technician1",
                FullName = "张三",
                Email = "zhangsan@company.com",
                Phone = "13888888888",
                Role = UserRole.Technician,
                Department = "维修部",
                CreatedAt = DateTime.Now.AddDays(-30)
            },
            new User
            {
                Id = 2,
                Username = "admin1",
                FullName = "李四",
                Email = "lisi@company.com",
                Phone = "13999999999",
                Role = UserRole.Admin,
                Department = "技术部",
                CreatedAt = DateTime.Now.AddDays(-30)
            }
        );

        modelBuilder.Entity<ExternalVendor>().HasData(
            new ExternalVendor
            {
                Id = 1,
                CompanyName = "专业维修公司A",
                ContactPerson = "王五",
                ContactPhone = "13777777777",
                ContactEmail = "wangwu@repair-a.com",
                Address = "上海市浦东新区科技路123号",
                CreatedAt = DateTime.Now.AddDays(-30)
            },
            new ExternalVendor
            {
                Id = 2,
                CompanyName = "设备维护中心B",
                ContactPerson = "赵六",
                ContactPhone = "13666666666",
                ContactEmail = "zhaoliu@repair-b.com",
                Address = "上海市徐汇区维修街456号",
                CreatedAt = DateTime.Now.AddDays(-30)
            }
        );
    }
} 